﻿//************************************************************************************************
// Copyright © 2012 Steven M. Cohn. All Rights Reserved.
//
//************************************************************************************************

namespace CookieChipper
{
	using System;
	using System.IO;


	/// <summary>
	/// Exports one or more cookies to a comma-separated text file suitable of
	/// opening with Excel or importing in a database for analysis.
	/// </summary>

	internal class CookieExporter : IDisposable
	{
		private const string DateFormat = "MM/dd/yyyy h:mm tt";

		private StreamWriter writer;
		private bool isDisposed;


		//========================================================================================
		// Lifecycle
		//========================================================================================

		/// <summary>
		/// Initialize a new exporter, opening a new file with the specified path.
		/// </summary>
		/// <param name="path"></param>

		public CookieExporter (string path)
		{
			writer = File.CreateText(path);
			writer.WriteLine("Domain,Name,Value,Hits,Created,Expires,Updated,Path");

			isDisposed = false;
		}


		public void Dispose ()
		{
			Dispose(true);
		}


		protected virtual void Dispose (bool disposing)
		{
			if (!isDisposed)
			{
				if (writer != null)
				{
					try
					{
						writer.Dispose();
					}
					catch
					{
					}
					finally
					{
						writer = null;
					}
				}

				isDisposed = true;
			}
		}


		//========================================================================================
		// Methods
		//========================================================================================

		/// <summary>
		/// Export all values of the given cookie.
		/// </summary>
		/// <param name="cookie"></param>
		/// <returns></returns>

		public int Export (Cookie cookie)
		{
			int count = 0;
			foreach (var chip in cookie.Values)
			{
				writer.WriteLine(
					"\"" + chip.Domain
					+ "\",\"" + chip.Name
					+ "\",\"" + chip.Value
					+ "\",\"" + cookie.Hits.ToString()
					+ "\",\"" + chip.Created.ToString(DateFormat)
					+ "\",\"" + chip.Expires.ToString(DateFormat)
					+ "\",\"" + cookie.Updated.ToString(DateFormat)
					+ "\",\"" + cookie.Path + "\"");

				count++;
			}

			return count;
		}
	}
}
